package com.abu.crms.template;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Data;
import org.apache.http.entity.FileEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.UUID;

@Data
@Component
@ConfigurationProperties(prefix = "ali.oss")
public class UploadTemplate {

    private String accessKeyId;

    private String accessKeySecret;

    private String endpoint;

    private String bucketName;

    public String toUpload(MultipartFile file ) throws IOException {
//        创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//        1. 命名文件夹名字
        String fileFolder = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//        2. 重新命名文件
        String uuid = UUID.randomUUID().toString();
        String originalFilename = file.getOriginalFilename();
//        3. 执行上传
        ossClient.putObject(bucketName, fileFolder + "/" + uuid + "-" + originalFilename, file.getInputStream());
//        4. 获取文件上传后的地址
//        https://upload-test-01.oss-cn-beijing.aliyuncs.com/20210406/e2367546-63a9-4848-92b9-aec1cfb3f738
        String avatarUrl = "https://" + bucketName + "." + endpoint + "/" + fileFolder + "/" + uuid + "-" + originalFilename;
//        5. 关闭OSSClient。
        ossClient.shutdown();
//        6.返回结果
        return avatarUrl;
    }


}
